import React, { Component } from 'react';
import { Form, Input, Radio, Select } from 'antd';
import { FormComponentProps } from 'antd/es/form';
import E from 'wangeditor';
import { addPosts, editPosts } from '@/services/appManage';
import ImageUpload from '@/components/ImageUpload';

interface IProps extends FormComponentProps {
  [propName: string]: any;
}

const config = {
  rules: [{ required: true, message: '不能为空!' }],
};

class FormContent extends Component<IProps> {
  readonly state: Readonly<any> = {
    style:
      Number(this.props.itemData.images.length) !== 0
        ? Number(this.props.itemData.images.length)
        : 1,
    editorContent: '',
  };

  public handlerChangeImgIds = (imageIds: string[]) => {
    this.props.form.setFieldsValue({ images: imageIds });
  };

  public handlerSubmit = () =>
    new Promise((resolve: Function) => {
      const { validateFields, setFieldsValue, getFieldValue } = this.props.form;
      setFieldsValue({ images: getFieldValue('images') });
      validateFields((err: any, value: any) => {
        if (!err) {
          if (this.props.isEdit) {
            editPosts({
              ...value,
              id: this.props.itemData.id,
              type: this.props.itemData.type,
            }).then((resp: any) => {
              resolve(resp);
            });
          } else {
            addPosts({
              ...value,
              type: this.props.itemData.type,
            }).then((resp: any) => {
              resolve(resp);
            });
          }
        } else {
          //  window.console.log((err);
        }
      });
    });

  public ImageUploadRef: any;

  public editorElem: any;

  public handleChange = (value: any) => {
    this.setState({
      style: value,
    });
  };

  public componentDidMount() {
    const elem = this.editorElem;
    const editor = new E(elem);
    // 使用 onchange 函数监听内容的变化，并实时更新到 state 中
    editor.customConfig.onchange = (html: any) => {
      this.setState(
        {
          editorContent: html,
        },
        () => {
          this.props.form.setFieldsValue({ content: this.state.editorContent });
        },
      );
    };
    editor.create();
    editor.txt.html(this.props.itemData.content);
    this.props.form.setFieldsValue({ content: this.props.itemData.content });
  }

  public render() {
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const radioData = [
      {
        value: true,
        label: '显示',
      },
      {
        value: false,
        label: '隐藏',
      },
    ];
    const { getFieldDecorator } = this.props.form;
    const { images, title, sort, status, type, summary } = this.props.itemData;
    console.log(images, 'images');
    return (
      <Form {...formItemLayout} onSubmit={this.handlerSubmit}>
        <Form.Item label="文章名称">
          {getFieldDecorator('title', {
            ...config,
            initialValue: title,
          })(<Input style={{ width: '350px' }} type="text" placeholder="请输入标题" />)}
        </Form.Item>
        <Form.Item label="选择图文样式">
          <Select
            value={this.state.style}
            style={{ width: 160 }}
            onChange={this.handleChange}
            disabled={type === 2}
          >
            <Select.Option value={1}>一张图片排版</Select.Option>
            <Select.Option value={3}>三张图片排版</Select.Option>
          </Select>
        </Form.Item>
        <Form.Item label="文章图片">
          {getFieldDecorator('images', {
            rules: [
              {
                validator: (rule: any, value: any, callback: any) => {
                  if (value.length !== this.state.style) {
                    callback(new Error('图片必须为一张或者三张'));
                  }
                  callback([]);
                },
                message: '图片必须为一张或者三张',
              },
            ],
            initialValue: images.map((item: any) => item.id),
          })(
            <ImageUpload
              ref={(node: any) => {
                this.ImageUploadRef = node;
              }}
              imageLength={this.state.style}
              handlerChangeImgIds={this.handlerChangeImgIds}
              defaultFileList={
                images.length > 0
                  ? images.map((image: any) => ({ uid: image.id, url: image.url }))
                  : undefined
              }
            />,
          )}
        </Form.Item>
        <Form.Item label="排序位置">
          {getFieldDecorator('sort', {
            rules: [
              { required: true, message: '不能为空!' },
              {
                pattern: new RegExp(/^\d+$/),
                message: '排序值必须是数字',
              },
            ],
            initialValue: sort,
          })(<Input style={{ width: '350px' }} type="text" placeholder="请输入标题" />)}
        </Form.Item>
        <Form.Item label="是否显示">
          {getFieldDecorator('status', {
            ...config,
            initialValue: status,
          })(
            <Radio.Group>
              {radioData.map(item => (
                <Radio value={item.value} key={item.label}>
                  {item.label}
                </Radio>
              ))}
            </Radio.Group>,
          )}
        </Form.Item>
        <Form.Item label="文章类型">
          {getFieldDecorator('type', {
            ...config,
            initialValue: type,
          })(
            <Radio.Group disabled>
              <Radio value={1}>图标文章</Radio>
              <Radio value={2}>动态文章</Radio>
            </Radio.Group>,
          )}
        </Form.Item>
        <Form.Item label="文章摘要">
          {getFieldDecorator('summary', {
            ...config,
            initialValue: summary,
          })(<Input style={{ width: '350px' }} type="text" placeholder="请输入标题" />)}
        </Form.Item>
        <Form.Item label="文章内容">
          {getFieldDecorator('content', {
            ...config,
          })(
            // <Input.TextArea
            //   autoSize={{ minRows: 4 }}
            //   style={{ width: '350px' }}
            //   placeholder="请输入文章内容"
            // />,
            <div
              ref={node => {
                this.editorElem = node;
              }}
              style={{ textAlign: 'left' }}
            ></div>,
          )}
        </Form.Item>
      </Form>
    );
  }
}

export default FormContent;
